package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.interceptors.LoginInterceptor;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.apache.http.impl.cookie.RFC2965DiscardAttributeHandler;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Response;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: 86182
 * @Date: 2021/8/20
 * @Time: 1:27
 * @Version:
 */
@Controller
public class CartController {
    @Autowired
    private CartService cartService;



    @GetMapping("check/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCheckedCarts(@PathVariable("userId") Long userId){
        List<Cart> carts = this.cartService.queryCheckedCarts(userId);
        return ResponseVo.ok(carts);
    }

    /**
     * 新增购物车方法
     * 参数cart中只有浏览器传递的: skuId 和 count
     * @param cart
     * @return
     */
    @GetMapping
    public String addCart(Cart cart){
        this.cartService.addCart(cart);
        //重定向到成功的方法路径
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    /**
     * 新增成功方法,展示新增购物车成功页面
     *参数cart中只有浏览器传递的:skuId 和 count
     * @param cart
     * @param model
     * @return
     */
    @GetMapping("addCart.html")
    public String queryCartBySkuId(Cart cart, Model model){
        BigDecimal count = cart.getCount();
        cart = this.cartService.queryCartBySkuId(cart.getSkuId());
        cart.setCount(count);
        model.addAttribute("cart",cart);
        return "addCart";
    }

    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> carts = this.cartService.queryCarts();
        model.addAttribute("carts",carts);
        return "cart";
    }
@PostMapping("updateNum")
@ResponseBody
public ResponseVo updateNum(@RequestBody Cart cart){
        this.cartService.updateNum(cart);
        return ResponseVo.ok();
}

@PostMapping("deleteCart")
@ResponseBody
public ResponseVo deleteCart(@RequestParam("skuId") Long skuId){
        this.cartService.deleteCart(skuId);
        return ResponseVo.ok();
}






    @GetMapping("test")
    @ResponseBody
    public String test(){
        System.out.println("============================test========" + LoginInterceptor.getUserInfo());
        return "hello test";
    }
}
